package com.lanxiao.cloud.modules.file.domain.service.impl;

import cn.hutool.core.util.IdUtil;
import com.google.gson.Gson;
import com.lanxiao.cloud.common.core.exception.BusinessException;
import com.lanxiao.cloud.modules.file.domain.model.FileConfigure;
import com.lanxiao.cloud.modules.file.domain.service.IUploadFileService;
import com.lanxiao.cloud.modules.file.infrastructure.enums.UploadType;
import com.lanxiao.cloud.modules.file.infrastructure.error.UploadErrorType;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ：qiaoliang
 * @date ：2021-10-25
 */
@Service
public class QiNiuYunUploadServiceImpl implements IUploadFileService {

  @Override
  public String uploadFile(MultipartFile file, FileConfigure fileConfigure) {
    Configuration cfg = new Configuration(Region.region0());
    UploadManager uploadManager = new UploadManager(cfg);
    Auth auth = Auth.create(fileConfigure.getAccessKey(), fileConfigure.getSecretKey());
    String upToken = auth.uploadToken(fileConfigure.getBucket());
    String uploadUrl = null;
    try {
      final InputStream inputStream = file.getInputStream();
      // 在文件名称中添加随机的唯一的值，防止名称一样时文件的覆盖
      String uuid = IdUtil.simpleUUID();
      Response response = uploadManager.put(inputStream, uuid, upToken, null, null);
      //解析上传成功的结果
      DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
      uploadUrl = "http://" + fileConfigure.getEndpoint() + "/" + putRet.key;
    } catch (IOException e) {
      e.printStackTrace();
      throw new BusinessException(UploadErrorType.UPLOAD_ERROR);
    }
    return uploadUrl;
  }

  @Override
  public UploadType only() {
    return UploadType.QINIUYUN;
  }

}
